from __future__ import absolute_import
import logging

from os.path import join #, exists

from forest.api import Command, get_tool

logger = logging.getLogger('forest.commands.SELinux')


class SELinux(Command):
    ''' Selects SELinux mode. Save yourself some headaches and disable it. ;-)

        We prefer::

            selinux:
                mode: disabled

    '''
    __register__ = 'commands.setup.SELinux'

    requires_config = ['selinux']

    def run(self, config):

        self.args = config.get('selinux')

        if not self.args:
            return

        se_mode = self.args.get('mode', None)
        se_type = self.args.get('type', None)
        install_tree = config.get_install_root()
        se_path = config.join_install_root('etc', 'selinux', 'config')
        get_tool('system.mkdir')(config.join_install_root('etc', 'selinux'))
        #if not exists(se_path):
        #    return

        selinux_lst = []
        if se_mode is not None:
            selinux_lst.append('SELINUX={0}'.format(se_mode))
        if se_type is not None:
            selinux_lst.append('SELINUXTYPE={0}'.format(se_type))
        selinux_lst.append('')
        get_tool('files.write')(se_path, '\n'.join(selinux_lst))
